package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.TUser;
import com.bwie.service.TUserService;
import com.bwie.mapper.TUserMapper;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import com.bwie.vo.TUserVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

/**
* @author 36167
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-03-12 09:21:43
*/
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService{

    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private String key="123456";


    @Override
    public R login(LoginInfoVo loginInfoVo) {
        if (StringUtils.isEmpty(loginInfoVo.getUserName())){
            return R.ERROR(500,"用户名不能为空");
        }
        if (StringUtils.isEmpty(loginInfoVo.getUserPass())){
            return R.ERROR(500,"密码不能为空不能为空");
        }

        LambdaQueryWrapper<TUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TUser::getUsername,loginInfoVo.getUserName());
        wrapper.eq(TUser::getPassword,loginInfoVo.getUserPass());

        TUser one = getOne(wrapper);
        if (one==null){
            return R.ERROR(500,"用户不存在");
        }
        //长期token
        String token = Jwts.builder().setExpiration(new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000))
                .signWith(SignatureAlgorithm.HS256, key).claim("uid", one.getId()).compact();
        //短期token
        String redistoken = Jwts.builder().setExpiration(new Date(System.currentTimeMillis() + 7200 * 1000))
                .signWith(SignatureAlgorithm.HS256, key).claim("uid", one.getId()).compact();
        stringRedisTemplate.opsForValue().set(redistoken,token);
        TUserVo tUserVo = new TUserVo();
        tUserVo.setRedistime(System.currentTimeMillis()+7200*1000);
        tUserVo.setRedistoken(redistoken);
        HashMap<String, Object> map = new HashMap<>();
        map.put("user",one);
        map.put("token",redistoken);
        return R.OK(map);
    }

    @Override
    public R user(Integer uid) {
        TUser tUser = tUserMapper.selectById(uid);
        return R.OK(tUser);
    }
}




